<!-- 技能树详情 -->
<template>
    <div class="pageWrap pageDetail">
        <!-- <div class="breakNav">
            <div class="addressIcon"></div>
            <span>当前位置:</span>
            <span style="cursor: pointer" @click="returnParent">技能树列表</span>
            <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
            <span style="color: #333">{{routeParams.name}}</span>
        </div> -->
        <div style="position:relative;background:#fff;height: 100%;overflow: hidden auto;">
            <section style="position:relative;padding:5px 16px" class="startLR">
                <div >
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />鼠标悬浮文字可以进行增加，修改，删除，配置，查看等操作</span></p>
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />非叶子节点才能进行添加操作，叶子节点才能配置，查看操作</span></p>
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />点击文字或原点可以展开或收缩该节点下所有子节点</span></p>
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />蓝色原点为岗位，绿色为技能，灰色为叶子节点</span></p>
                </div>
                <div>
                    <Button type="primary" :disabled="hasRoot" ghost class="md-add-jh" @click="showAddRoot">创建根节点</Button>
                </div>
                 <!-- <section v-if="relativeList.length" class="leftVH">
                    <h4>{{svgData.data.name}}</h4>
                    <Tag v-for="t in relativeList" :key="t.id">{{t.id}}</Tag>
                </section> -->
            </section>
            <div style="position:relative">
              <div id="oprateDiv" v-show="editGroup"  style="position:absolute;z-index:99999;us:20px;padding:2px 8px;font-size:20px;background:#fff">
                <Icon title="创建" @click.native="append($event,svgData)"  type="ios-add-circle-outline" v-if="!svgData.data.isLeafNode" />
                <!-- v-if="svgData.data.isLeafNode"  -->
                <Icon title="绑定训练内容" @click.native="appendRelative($event,svgData)"  type="ios-infinite-outline"/>
                <!-- <Icon title="查看绑定内容详情" @click.native="showLeaftDetail($event,svgData)" type="ios-apps-outline" v-if="svgData.data.isLeafNode" /> -->
                <span>
                     <Icon  title="修改" @click.native ="editTree($event,svgData)"  type="ios-brush-outline" />
                </span>
               <span>
                   <Poptip
                    confirm
                    class="delBox"
                    title="确定要删除吗?"
                    @on-ok="delItem(svgData)">
                     <Icon title="删除" type="ios-trash-outline" />
                </Poptip>
               </span>
            </div>
            <!-- <div v-if="oprateModal" class="modal-mask" ></div>
            <div v-if="oprateModal" class="modal-class" :style="{left:divLeftM,top:parseInt(divTop)+36+'px'}"> -->
                
                <!-- </div> -->
            <section id="showTree">
                <SkillTree id="showTree" poptipId="oprateDiv"></SkillTree>
              <svg :width="svgW" :height="svgH"></svg>              
            </section>
            </div>
        </div>
        <Modal
                    v-model="oprateModal"
                    :title="!editState?'创建节点':'修改节点'"
                    @on-cancel="closeModal"
                    @on-ok="dSubmitBtn"
                    :mask-closable="false"
                    :width="800"
                    :loading="load"
                    style="min-width:540px;width:auto"
                >
                <!-- :footer-hide="true" -->
                    <div class="modal-header" v-if="svgData.data.name" >
                        <Tooltip max-width="260" :content="svgData.data.name">
                            <h4 class="mgr15 font14 node-css">{{isRoot?'节点名称':'上层节点'}}：{{svgData.data.name}}</h4>
                        </Tooltip>
                         <Tag color="blue" v-if="svgData.data.difficulty">{{mapDifficulty(svgData.data.difficulty)}}</Tag>
                         <Tag color="blue" v-if="svgData.data.type">{{mapType(svgData.data.type)}}</Tag>
                         <Tag color="blue" v-if="svgData.data.typeCode">{{mapTypeCode(svgData.data.typeCode)}}</Tag>
                    </div>
                    <div class="modal-content">
                        <span v-if="!editState" class="addType">
                              <label for="addtype">创建方式</label>
                              <RadioGroup id="addtype" v-model="addType"  @on-change="changeAddType" >
                                <Radio :label="1">从已存在的技能树中添加</Radio>
                                <Radio :label="0">直接创建</Radio>  
                              </RadioGroup>
                        </span>
                        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" class="primaryBgColor">
                            <span v-if="addType==1">
                              <!-- 从技能树中添加 -->
                              <div class="startLR">
                                <div class="whiteBgColor preLeft">
                                  <Input suffix="ios-search" search v-model="queryObj.name" placeholder="输入技能树名称" @on-search="searchTree" style="width: auto" />
                                  <ul class="treelist">
                                    <li :class="list.name==activeName?'active':''" v-for="list in treeList" :key="list.id" @click="setSmallTreePre(list.id,list.name)" ><a>{{list.name}}</a></li>
                                  </ul>
                                   <Page class="mt16" :total="treeListTotal" show-elevator show-total @on-change="pageChange" 
                                   @on-page-size-change="sizeChange" />
                                </div>
                                <div class="listItemTreePre whiteBgColor" @contextmenu="handlePaste($event)">
                                  <h4 class="pd15">预览区
                                      <p><span style="color:#f90;margin-right:16px;line-height: 35px;"> <Icon type="ios-information-circle-outline" />点击右键可用复制当前节点以及下面的所有子节点，点击确定按钮将当前复制的内容插入到当前打开的节点中</span></p>
                                      <p><span style="color:#f90;margin-right:16px;line-height: 35px;"> <Icon type="ios-information-circle-outline" />创建根节点的时候不能复制叶子节点</span></p>
                                  </h4>
                                  <div id="preTree">
                                    <svg :width="svgWs" :height="svgHs"></svg>
                                  </div>
                                  <!-- <d-3-tree :data="preData" :options="preOptions" @domclick="svgClick"/> -->
                                </div>
                              </div>
                            </span>
                            <span v-if="addType==0">
                              <!-- 直接添加 -->
                              <FormItem label="名称" prop="name" key="name">
                                <Input v-model="formValidate.name" placeholder="请输入名称"></Input>
                                </FormItem>
                                <FormItem label="类型" prop="type" key="type">
                                  <RadioGroup v-model="formValidate.type">
                                      <Radio label="1">岗位</Radio>
                                      <Radio label="2">技能</Radio>
                                  </RadioGroup>
                                </FormItem>
                                <FormItem label="等级" prop="difficulty" key="difficulty">
                                  <RadioGroup v-model="formValidate.difficulty">
                                      <Radio label="low" :disabled="skillLearn&&editState">初级</Radio>
                                      <Radio label="middle" :disabled="skillLearn&&editState">中级</Radio>
                                      <Radio label="high" :disabled="skillLearn&&editState">高级</Radio>                                     
                                  </RadioGroup>
                                </FormItem>
                                <FormItem label="叶子节点" prop="isLeafNode" key="isLeafNode">
                                  <RadioGroup v-model="formValidate.isLeafNode">
                                      <Radio :label="0" :disabled="isRoot||editState">否</Radio>
                                      <Radio :label="1" :disabled="isRoot||editState">是</Radio>
                                  </RadioGroup>
                                </FormItem>
                                <FormItem label="图片" prop="image">
                                    <ItemUpload
                                        ref="imageUpload"
                                        :formatArr="['jpg','jpeg','png']" 
                                        fileType="images"
                                        @upload-success="getUrl"
                                    ></ItemUpload>
                                    <div class="chose-wrap" v-show="formValidate.image">
                                        <div class="chose-name">
                                            <img :src="handleImage(formValidate.image)">
                                        </div>
                                        <img src="../../../assets/globalIcon/dis-del.png" @click="formValidate.image = ''">
                                    </div>
                                </FormItem>
                                <FormItem label="技能方向" prop="direction" v-if="formValidate.isLeafNode" key="direction">
                                  <Select filterable v-model="formValidate.direction" placeholder="选择技能方向" :disabled="formValidate.points&&Boolean(formValidate.points.length)" @on-change="setDictTypeCode">
                                      <Option v-for="item in dictListDirection" :value="item.dictid" :key="item.dictid">{{item.dictname}}</Option>
                                  </Select>
                                </FormItem>
                                <FormItem label="技能类型" prop="typeCode" v-if="formValidate.isLeafNode" key="typeCode">
                                  <Select filterable v-model="formValidate.typeCode" :disabled="formValidate.points&&Boolean(formValidate.points.length)" placeholder="选择技能类型">
                                      <Option v-for="item in dictListTypeCode" :value="item.dictid" :key="item.dictid">{{item.dictname}}</Option>
                                  </Select>
                                </FormItem>
                                <FormItem label="过关条件" prop="extension" v-if="formValidate.isLeafNode" key="extension">
                                  <!-- <Input type="textarea" :autosize="{minRows: 2,maxRows: 5}" v-model="formValidate.extension" placeholder='请用JSON格式输入入过关条件，类似{"a":"bb"}'/> -->
                                  <div v-for="rule in ruleList" :key="rule.id" style="margin-bottom:12px"> 
                                       <Select filterable :disabled="true" v-model="rule.type"  placeholder="配置过关规则" style="width: 160px">
                                            <!-- 类型：0.课程、1.课件、2.视频、3.考试、4.场景 -->
                                            <Option :value="0" >课程</Option>
                                            <Option :value="1" >课件</Option>
                                            <Option :value="2" >视频</Option>
                                            <Option :value="3" >考试</Option>
                                            <Option :value="4" >场景</Option>
                                        </Select>
                                        <Input  @on-blur="setExtensionInput(rule)" :disabled="rule.type==0||rule.type==1||rule.type==2" v-model="rule.content"  placeholder="输入规则信息" style="width: 200px" />
                                        <span style="color:#f90;margin-right:16px;line-height: 35px;" v-if="rule.type==0||rule.type==1||rule.type==2">默认使用{{mapTypeRule[rule.type]}}已学规则</span>
                                        <span style="color:#f90;margin-right:16px;line-height: 35px;" v-if="rule.type==3">默认考试总分的60%为通过</span>
                                        <span style="color:#f90;margin-right:16px;line-height: 35px;" v-if="rule.type==4">默认完成场景内50%以上的靶标题目或者任务</span>
                                  </div>
                                  </FormItem>
                            </span>
                        </Form>
                         <!-- <div class="oprateBtn">
                            <Button type="primary" @click="submitBtn('formValidate')" >确定</Button>
                        </div> -->
                    </div>
                    </Modal>
        <skill-tree-plan ref="skillTreePlan"></skill-tree-plan>
    </div>
</template>

<script>
    import $ from 'jquery'
    import encryption from '@/libs/encryption.js'
  	import usally from '@/mixin/usally'
    import { experType } from '@/api/dict'
    import skillTreeMixin from './tree3.js'
    import {querySkillChapter,delSkillChapter,addSkillChapter,
    modifySkillChapter,querySkill,nodeCopy,querySkillPoint,getSysConfig} from '@/api/selfStudy/skill.js'
    import skillTreePlan from './skillTreePlan.vue'
    import { debounce,throttle } from '@/libs/utils'
    import Popper from 'popper.js/dist/umd/popper.js'
    import ItemUpload from '@/components/item-upload'
    import SkillTree from './tree.vue'
    export default {
        name: "chapters",
        components:{skillTreePlan ,ItemUpload,SkillTree},
		props:[],
        mixins:[usally,skillTreeMixin],
        data () {
             const validateJSON = (rule, value, callback) => {
                if (value) {
                    try{
                         let json = JSON.parse(value).extension;
                        let flag = json.every(item=>item.content);
                        if(flag){
                             const reg = /^[123456789]\d*$/;
                            if(reg.test(json[3].content)&&reg.test(json[4].content)){
                                let v = json[3].content;
                                let s = json[4].content;
                                v = v*1;
                                s = s*1;
                                if((v>0&&v<=100)&&(s>0&&s<=100)){
                                    callback();
                                }else{
                                    callback(new Error('请输入0-100之间的数字'));
                                }
                            }else{
                                callback(new Error('请输入大于0的数字'));
                            }
                        }else{
                            callback(new Error('输入考试或场景规则'));
                        }
                    }catch(err){
                        callback(new Error('请输入json格式的字符串'))
                    }
                } else {
                    callback(new Error('请输入过关条件'));
                }
            };
            let September = sessionStorage.getItem('November')
			September = JSON.parse(encryption.SelfUseDecrypt(September));
            return {
                USER_ID:September.userId,
				USER_Name:September.nickname,
				isRootDesigner:September.isRootDesigner,
                passRuleType:0,
                ruleId:1,
                passRuleContent:'',
                load:true,
                addType:0,
                isRoot:false,
                ruleListCopy:[
                    {type:0,content:'默认'},
                    {type:1,content:'默认'},
                    {type:2,content:'默认'},
                    {type:3,content:'60'},
                    {type:4,content:'50'},
                ],
                ruleList:[],
                queryObj:{
                    pageIndex:1,
                    pageSize:10,
                    name:'',
                    available:1
                },
                routeParams:{},
                currentCopy:{},
                hasRoot:true,
                divLeft:'0px',
                divLeftM:'0px',
                divTop:'0px',
                oprateModal:false,
                svgW:0,
                svgH:0,
                svgHs:0,
                svgWs:0,
                zIndex:-1,
                divScale:1,
                searchName:'',
                editGroup:false,
                currentData:{},
                svgData:{
                    data:{}
                },
                //tree
                editState:false,
                treeDataList:[],
                buttonProps: {
                    type: 'default',
                    size: 'small',
                },
                // 输入框要修改的内容
                inputContent:"",
                // 修改前的TreeNode名称
                oldName:"",
                showDefImg:true,
				showDefText:"加载中",
                fullHeight: document.documentElement.clientHeight,
                fullWidth: document.documentElement.clientWidth,
                contentHei:'auto',
                updateChapterArea: false,
                // 页面标题
                titleText:'权重配置',
                complete:false,
                parentItem:{},
                addItemObj:{},
                currentAddIndex:0,
                addItemLenth:0,
                activeName:'',
                endLevel:1,
                addItems:[],
                dictList:[],
                dictListDirection:[],
                dictListTypeCode:[],
                skillLearn:false,
                // 方案id
                weightId:'',
                weightName:'',
                // 段落列表
                chapterData:[],
                originLinkData:[],
                currData:{},
                odlEditTreeChapter:{},
                currParentChapter:{},
                // 创建技能树
                level:1,
                formValidate: {
                    name:'',
                    difficulty:'low',
                    typeCode:'',
                    direction:'',
                    isLeafNode:0,
                    type:'1',
                    extension:JSON.stringify({extension:this.ruleList}),
                    image:''
                },
                ruleValidate: {
                    name: [
                        { required: true,   message: '请输入名称', trigger: 'change'},
                        { type: 'string', max:24, message: '名称最长为24个字符', trigger: 'change' }
                    ],
                    difficulty: [
		                { required: true,  message: '请选择等级', trigger: 'change' }
	                  ],
                      type: [
		                { required: true,  message: '请选择类型', trigger: 'change' }
	                  ],
                      isLeafNode:[
                        { required: true, type:'number', message: '请选择是否为叶子节点', trigger: 'change' }
                      ],
	                  typeCode: [
		                { required: true,  message: '请选择技能类型', trigger: 'change' }
	                  ],
                      direction:[
                          { required: true,  message: '请选择技能方向', trigger: 'change' }
                      ],
                      extension:[
                        { required: true,  message: '请输入过关条件', trigger: 'change' },
                        {validator: validateJSON,trigger: 'change'}
                      ]
                },
                defaultVal:'',
                treeList:[],
                treeListTotal:0,
                mapTypeCodeObj:{},
                relativeList:[],
                currentRule:{},
                mapTypeRule:{
                    0:'课程',
                    1:'课件',
                    2:'视频'
                }
            }
        },
        computed:{},
        mounted(){
            window.onresize = () => {
                this.resizeThrottle()
            }
          //获取字典下的所有方向
          this.queryWeightList();
          this.getSkillLearn();
          //获取路由参数
          this.routeParams = {...this.$route.query}
          this.$store.commit('addBreadItem', { name: this.routeParams.name });
          this.setSvgWH();
          this.queryDetail(this.routeParams.id,{id:'showTree',width:this.svgW,height:this.svgH,cb:this.handlerDataUpdate,leaft:this.leaftDetail,clear:this.clearData},'init');
        },
        beforeRouteLeave (to, from, next) {
            if(to.path === '/skillTreeManage'){
                to.query.inPage = this.$route.query.inPage
                next()
            }else {
            	//跳转至非方案管理页面，清空存储的查询条件
				    sessionStorage.removeItem("queryObj");
                next()
            }
        },
        methods:{
             getSkillLearn(){
                getSysConfig({name:'skillTreeLearningSequenceControl'}).then(res=>{
                    if(res.code==1){
                    this.skillLearn = res.attribute.data.value==1?true:false;
                    }
                })
            },
            //resize节流
            resizeThrottle:throttle(function(){
                this.setSvgWH();
                this.queryDetail(this.routeParams.id,{id:'showTree',width:this.svgW,height:this.svgH,cb:this.handlerDataUpdate,leaft:this.leaftDetail,clear:this.clearData},'init');
            },1000),
            //设置svg的宽高
            setSvgWH(){
              const width = document.documentElement.clientWidth - 260;
              const height = document.documentElement.clientHeight - 260;
              this.svgW = width;
              this.svgH = height;
              this.svgWs = this.svgW/1.2<1200?1200:this.svgW/1.2;
              this.svgHs = this.svgH/1.2<800?800:this.svgH/1.2
            },
            setExtensionInput(rule){
                const index = this.ruleList.findIndex(i=>i.type==rule.type);
                this.formValidate.extension = JSON.stringify({extension:this.ruleList});
                this.$refs.formValidate.validateField('extension')
                console.log(this.formValidate.extension)
            },
            //获取数据,渲染列表
            queryDetail(id,options,type){
              querySkillChapter(id).then(res=>{
                if(res.code==1){
                  this.datasource = res.data.items;
                  //const datas = {name:name,children:this.datasource}
                  const datas = this.datasource[0];
                  if(type=='init'){
                      if(datas){
                      this.hasRoot = true;
                        }else{
                            this.hasRoot = false;
                        }
                  }
                  console.log('root',this.hasRoot)
                  this.initTree(datas,options)
                }
              })
            }, 
            mapDifficulty(d){
                const mapd = {
                    'high':'高级',
                    'middle':'中级',
                    'low':'初级'
                }
                return mapd[d];
            },
            mapTypeCode(code){
                return this.mapTypeCodeObj[code]
            },
            mapType(t){
                const mapt = {
                    1:'岗位',
                    2:'技能'
                }
                return mapt[t];

            },
            // 返回方案管理
            returnParent(){
                this.$router.push({
                    name: 'skillTreeManage',
                    query:{
                        inPage:this.$route.query.inPage,
                    }
                })
            },
            //获取所有能力列表
            showAddRoot(){
                 let aa = this.isSelfOprate();
                if(aa){
                    return;
                }
                this.isRoot = true;
                this.editState = false;
                this.oprateModal = true;
                this.formInitFn();
                this.svgData.data = {};
                this.formValidate.isLeafNode = 0;
                 //获取所有的技能树
                this.getTreeList();
            },
            closeModal(){
                this.isRoot = false;
                this.oprateModal = false;
                this.formInitFn();
                this.$refs.formValidate.resetFields();
            },
            // Tree修改按钮
            editTree(event, svgData){
                 //获取所有的技能树
                 let aa = this.isSelfOprate();
                if(aa){
                    return;
                }
                this.editGroup = false;
                 this.addType = 0;
                this.getTreeList();
                this.oprateModal = true;
                const data =svgData&& svgData.data;
                event.stopPropagation()
                this.editState = true;
                this.currentData = JSON.parse(JSON.stringify(data)); 
                const direction = this.findDirection(data.typeCode);
                this.setDictTypeCode(direction)
                this.ruleList =data.extension?[...JSON.parse(data.extension)]:JSON.parse(JSON.stringify(this.ruleListCopy))
                this.formValidate = {...data,direction:direction};
                this.formValidate.extension = JSON.stringify({extension:this.ruleList})
            },
            findDirection(typecode){
                const dict = this.dictList.filter(item=>item.dictid==typecode)[0];
                if(dict){
                    return dict.parentid
                }else{
                    return ''
                }

            },
            appendFn(data){
                this.editState = false;
                this.currentData = JSON.parse(JSON.stringify(data));
                this.currentDataChildren = this.currentData.children?this.currentData.children.map(m=>m.abilityId):[];
                this.level = this.currentData.dirLevel+1;
                this.currentLevel = data.dirLevel+1
                this.preCurrentTotal = this.getCurrentLevelTotal();
                console.log('ttt',this.currentData);
                this.weightAddOrUpdate = false;
                this.abilityAddOrUpdate = true;
            },
            //判断是否为本人
            isSelfOprate(){
                if((!this.isRootDesigner)&&(this.$route.query.create!=this.USER_ID)){
                    this.$Message.info('仅当前登录用户或单位管理员能进行创建、修改、删除或绑定等操作')
                    return true;;
                }else if(JSON.parse(this.$route.query.collect)){
                    this.$Message.info('当前技能树已被收藏，无法变更')
                    return true;;
                }else{
                    return false;
                }
            },
            // 添加按钮
             append (event, data) {
                event.stopPropagation();
                let aa = this.isSelfOprate();
                if(aa){
                    return;
                }
                this.editGroup = false;
                this.oprateModal = true;
                this.$refs.formValidate.resetFields();
                this.ruleList = JSON.parse(JSON.stringify(this.ruleListCopy));
                 //获取所有的技能树
                this.getTreeList();
                this.creatParentBtn('formValidate')    
            },
            delItem(svgData){
                 let aa = this.isSelfOprate();
                if(aa){
                    return;
                }
                const data = svgData.data;
                delSkillChapter(data.id).then(res=>{
                    if(res.code==1){
                        this.$Message.info('删除数据成功');
                        this.queryDetail(this.routeParams.id,{id:'showTree',width:this.svgW,height:this.svgH,cb:this.handlerDataUpdate,leaft:this.leaftDetail,clear:this.clearData});
                        this.oprateModal = false;
                        if(!data.parentId){
                            this.hasRoot = false;
                        }
                    }else{
                        this.$Message.error(res.message)
                    }
                })
            },
            formInitFn(){
                this.addType = 0;
                this.formValidate = {
                    name:'',
                    difficulty:'low',
                    typeCode:'',
                    direction:'',
                    isLeafNode:0,
                    type:'1',
                    extension:JSON.stringify({extension:this.ruleList}),
                    image:''
                };
                this.$refs.formValidate.resetFields()
            },
             // 创建按钮
            creatParentBtn(){
                this.abilityAddOrUpdate = false;
                this.weightAddOrUpdate = true;
                this.editState = false;
                this.formInitFn()
            },
            dSubmitBtn:debounce(function(){
                this.submitBtn();
            },1000),
            submitBtn(){
               if(this.addType==1){//从模板中添加
                  const passObj = this.currentCopy.data;
                  const parentId = this.svgData.data.id;
                  const skillId = this.routeParams.id;
                  const params = {
                      dstCareerSkillId:skillId,
                      dstParentId:parentId
                  }
                  if(!params.dstParentId) delete params.dstParentId;
                  if(!passObj){
                      this.$Message.info('您尚未复制节点，请先复制!');
                      this.setLoad()
                      return false;
                  }
                  nodeCopy(params,passObj).then(res=>{
                    if(res.code==1){
                      this.$Message.info('复制技能节点成功');
                      this.oprateModal = false;
                      this.queryDetail(this.routeParams.id,{id:'showTree',width:this.svgW,height:this.svgH,cb:this.handlerDataUpdate,leaft:this.leaftDetail,clear:this.clearData});
                      this.isRoot = false;
                      this.hasRoot = true;
                    }else{
                      this.$Message.error(res.message);
                      this.setLoad();
                    }
                  })
               }else{//直接添加
                 this.$refs.formValidate.validate((valid) => {
                    if (valid) {
                        let apiInterFace;
                        let txt = '添加'
                        let {name,difficulty,dirLevel,label,isLeafNode,type,typeCode,extension,id,parentId,image} = this.formValidate;
                        //extension处理---extension原始值
                        let originExtension = [
                            {type:0,content:'default'},
                            {type:1,content:'default'},
                            {type:2,content:'default'},
                            {type:3,content:60},
                            {type:4,content:50}
                        ];
                        originExtension.forEach(item=>{
                            if(extension){
                                const e = JSON.parse(extension)
                                const i = e.extension.filter(f=>f.type==item.type)[0];
                                if(i){
                                    item.content = i.content;
                                }
                            }
                        })
                        const extensionStr = JSON.stringify(originExtension)
                        let passObj = {
                                    "careerSkillId": this.routeParams.id,//技能树id
                                    "difficulty": difficulty,
                                    "dirLevel": dirLevel,
                                    "extension": extensionStr,
                                    "isLeafNode": isLeafNode,
                                    "label": label,
                                    "name": name,
                                    "parentId": this.svgData.data.id,
                                    "type": type,
                                    "typeCode": typeCode,
                                    image
                                    //"typeId": "string"
                                }
                         
                        if(this.editState){
                            passObj.id = id;
                            passObj.parentId = parentId;
                            apiInterFace = modifySkillChapter;
                            txt = '修改'
                        }else{
                             apiInterFace = addSkillChapter
                            if(this.isRoot){//如果是根节点
                                delete passObj.parentId;
                                passObj.dirLevel = 1;
                                passObj.label = 1;
                            }else{
                                let label = this.svgData.data.children.length+1;
                                passObj.dirLevel = this.svgData.data.dirLevel+1;
                                passObj.label = label;
                            }
                             txt = '创建'
                        }
                        if(!isLeafNode){//如果不是叶子节点，删除extension字段
                            delete passObj.extension;
                            delete passObj.typeCode;
                           // delete passObj.difficulty;
                        }
                       // this.setLoad();
                        
                        console.log(passObj)
                       apiInterFace(passObj).then(res=>{
                           if(res.code==1){
                               this.$Message.info(txt+'技能树节点成功');
                               this.oprateModal = false;
                               if(this.isRoot){
                                   this.isRoot = false;
                                   this.hasRoot = true;
                               }
                               this.queryDetail(this.routeParams.id,{id:'showTree',width:this.svgW,height:this.svgH,cb:this.handlerDataUpdate,leaft:this.leaftDetail,clear:this.clearData});
                           }else{
                               this.$Message.error(res.message);
                               this.setLoad();
                           }
                       })
                    } else {
                        this.$Message.error('表单输入有误,请按提示输入');
                        this.setLoad();
                    }
                })

               }
            },
            setLoad(){
                this.load = false;
                this.$nextTick(()=>{
                    this.load = true;
                })
            },
            setDictTypeCode(id){
                this.dictListTypeCode = this.dictList.filter(item=>item.parentid==id);
            },
            //获取权重列表
            async queryWeightList(){
                const {code,attribute,message} = await experType('newDirectionType');
                if(code==1){
                    this.dictList = attribute.attribute[0].dictEntryList;
                    this.dictListDirection = this.dictList.filter(item=>!item.parentid);
                    this.dictListTypeCode = this.setDictTypeCode(this.dictListDirection[0].dictid)
                    this.dictList.forEach(item=>{
                        this.mapTypeCodeObj[item.dictid] = item.dictname
                    })
                }else{
                    this.$Message.error(message)
                }
            },
            //外部js调用的函数
            handlerDataUpdate({boolean,left,top,data,modalHide,el}){
                this.editGroup = boolean;
                if(boolean==false){
                    return
                }
                this.svgData = data || {data:{}};
                this.tooltip = new Popper(el, document.getElementById("oprateDiv"), {
					placement: 'top'
				});
            }, 
            hideOprate(){
                if(this.editGroup){
                   this.editGroup = false;
                }
            },
            showOprate(){
                this.editGroup = true;
            },
            alertMsg(){
                this.$Message.info('根节点不能复制叶子节点')
            },
            setSmallTreePre(id,name){
              if(id){
                  this.activeName = name;  
                  this.queryDetail(id,{width:400,height:300,id:'preTree',
                  cb:this.addDataFromTree,'font-size':'16px',isRoot:this.isRoot,
                  alertMsg:this.alertMsg
                  })
              }else{
                  this.initTree(null,{id:'preTree'})
              }
            },
            searchTree(){
                this.queryObj.pageIndex = 1;
                this.getTreeList()
            },
            getTreeList(){
                let params = {...this.queryObj}
                if(!this.queryObj.name){
                    delete params.name
                }
              querySkill(params).then(data=>{
                    if(data.code===1){
                        this.treeList = data.data.items;
                        this.treeListTotal = data.data.total;
                        const defaultVal = this.treeList[0];
                        if(defaultVal){
                            this.setSmallTreePre(defaultVal.id,defaultVal.name)
                        }else{
                            this.setSmallTreePre(null,null)
                        }
                    }else{
                        this.$Message.error(res.message)
                    }
                })
            },
            pageChange(page){
              this.queryObj.pageIndex = page;
              this.getTreeList()
            },
            sizeChange(size){
              this.queryObj.pageSize = size;
              this.getTreeList()
            },
            changeAddType(val){
                this.queryObj.name = ''; 
               if(val==1){
                this.$nextTick(()=>{
                  let defaultVal = this.treeList[0];
                  if(defaultVal){
                    this.setSmallTreePre(defaultVal.id,defaultVal.name)
                  }else{
                    this.setSmallTreePre(null,null)
                  }
                })
              }
            },
            addDataFromTree(data){
              //console.log(data);
              this.currentCopy = data ||{};
              //this.$Message.info('节点复制成功')
            },
            //禁用右键
            handlePaste(e){
                 e.preventDefault()
                return false
            },
            //创建叶子节点关系
            appendRelative(e,data){
                
                 e.stopPropagation();
                 let aa = this.isSelfOprate();
                 this.editGroup = false;
                this.$refs.skillTreePlan.openModel(data.data,aa)
            },
            //展示叶子节点信息
            leaftDetail(id){
                let params = {
                    pageIndex:1,
                    pageSize:9999,
                    chapterId:id
                }
                querySkillPoint(params).then(res=>{
                    if(res.code==1){
                    this.relativeList = res.data.items;
                    }else{
                    this.$Message.error(res.message)
                    }
                })
            },
            clearData(){
                this.relativeList = [];
            },
            showLeaftDetail(e,data){
                this.editGroup = false;
                this.$refs.skillTreePlan.openModel(data.data,'detail')
            },
            getUrl(file) {
                this.formValidate.image = file.filePath;
            },
            handleImage(logo) {
				let src = ''
				if(logo) {
					if(logo.indexOf('Learn') > -1) {
						src = logo
					} else {
						src = `/Learn/${logo}`
					}
				} 
                // else {
				// 	src = this.defaultImg
				// }
				return src
			},
        },
    }
</script>
<style scoped src="./skill.css"></style>
<style scoped>
.chose-wrap {
    display: flex;
    justify-content: space-between;
    padding: 3px 8px;
    background-color:var(--table-tr-hover-color);
    align-items: center;
    margin-top: 10px;
}

.chose-name {
    width: 300px;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.tip{
    color:#f90;
    margin-right:16px;
    line-height: 35px;
}
.pageWrap {
  height: calc(100vh - 60px);
}
</style>

